package com.wongleoi.weather_demo

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.wongleoi.weather_demo.data.Result
import com.wongleoi.weather_demo.data.WeatherRepository
import com.wongleoi.weather_demo.model.Weather
import kotlinx.coroutines.flow.flow

class WeatherViewModel(private val weatherRepository: WeatherRepository = WeatherRepository()) :
    ViewModel() {

    val cityWeather = MutableLiveData<Weather>()
    val loading = MutableLiveData(false)

    /**
     * 城市天气预报
     */
    fun weatherInfo(key: String,
                     city: String,
                     extensions: String,
                     output: String) = flow<Result<List<Weather>>> {
        try {
            val data = weatherRepository.weatherInfo(key, city, extensions, output).toMutableList()
            emit(Result.Success(data))
        } catch (e: Exception) {
            emit(Result.Error(e))
        }
    }


}